package com.qiantu.phone.ui.fragment.device;

import android.graphics.Color;
import android.view.View;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.api.entity.ControlDataColorTemperatureBean;
import com.qiantu.phone.ui.adapter.ColorTemperatureAdapter;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.ColorTemperatureSeekBar;
import com.qiantu.phone.widget.RoundSeekBar;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 *    desc   : 色温设备
 */
public final class ColorTemperatureFragment extends BaseDeviceFragment {

    private RoundSeekBar roundSeekBar;
    private RecyclerView colorTemperatureRecyclerView;
    private ColorTemperatureSeekBar colorTemperatureSeekBar;
    private ColorTemperatureAdapter mColorTemperatureAdapter;
    private ControlDataColorTemperatureBean mColorTemperatureInfo;
    private ControlDataColorTemperatureBean.ControlData controlData;

    public static ColorTemperatureFragment newInstance() {
        ColorTemperatureFragment fragment = new ColorTemperatureFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_color_temperature;
    }

    @Override
    protected void initView() {
        super.initView();
        roundSeekBar = findViewById(R.id.round_seek_bar);
        roundSeekBar.setOnChangeListener(new RoundSeekBar.OnChangeListener(){

            @Override
            public void onProgressChanged(int value) {

            }

            @Override
            public void onStopTrackingTouch(int value) {
                if(value == 0){
                    switchOperation(0);
                }else{
//                    DeviceState deviceState = mDevice.getStateData();
//                    Integer light = deviceState.getStatus().getLight();
//                    if(Float.valueOf(light) != value){
//                        lightOperation(value);
//                    }
                    lightOperation(value);
                }
//                setStatusBySwitch(value > 0);
            }

            @Override
            public void onSwitch(boolean isOpen) {
//                setStatusBySwitch(isOpen);
                roundSeekBar.setOpenState(!isOpen);
                switchOperation(isOpen ? 1 : 0);
            }
        });
        colorTemperatureRecyclerView = findViewById(R.id.color_temperature_recycler_view);
        colorTemperatureSeekBar = findViewById(R.id.color_temperature_seek_bar);
        colorTemperatureSeekBar.setOnSeekBarChangeListener(new ColorTemperatureSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int colorTemp) {

            }

            @Override
            public void onStartTrackingTouch() {

            }

            @Override
            public void onStopTrackingTouch(int colorTemp) {
                setKelvinItem(colorTemp);
                kelvinOperation(colorTemp);
            }
        });
        mColorTemperatureInfo = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataColorTemperatureBean.class);
        controlData = mColorTemperatureInfo.getControlData();
        ControllerBean mController = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(mDevice.getControllerSerialNo());
        if(mController.getProductModel().equals("0x0008")){//tld-8 负载方案2
            controlData.setColourtemperature_min(0);
        }
        colorTemperatureSeekBar.setMinMaxValue(controlData.getColourtemperature_min(), controlData.getColourtemperature_max());
        if(controlData.getColorData() != null && controlData.getColorData().size() > 0){
            mColorTemperatureAdapter = new ColorTemperatureAdapter(getContext());
            mColorTemperatureAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    if(roundSeekBar.isOpen()){
                        mColorTemperatureAdapter.selectItem(position);
                        ControlDataColorTemperatureBean.ColorData colorData = mColorTemperatureAdapter.getData().get(position);
                        colorTemperatureSeekBar.setColorTemp(colorData.getValue());
                        kelvinOperation(colorData.getValue());
                    }
                }
            });
            colorTemperatureRecyclerView.setAdapter(mColorTemperatureAdapter);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), controlData.getColorData().size());
            colorTemperatureRecyclerView.setLayoutManager(gridLayoutManager);
            mColorTemperatureAdapter.setData(controlData.getColorData());
            int[] gradientColors = new int[controlData.getColorData().size()];
            for(int i=0; i<controlData.getColorData().size(); i++){
                ControlDataColorTemperatureBean.ColorData colorData = controlData.getColorData().get(i);
                String color = colorData.getColor_16();
                gradientColors[i] = Color.parseColor(color);
            }
            colorTemperatureSeekBar.setGradientColors(gradientColors);
        }
        updateView();
    }

    private void setKelvinItem(int kelvin){
        if(controlData.getColorData() != null){
            boolean hasSame = false;
            for(int i=0; i<controlData.getColorData().size(); i++){
                ControlDataColorTemperatureBean.ColorData colorData = controlData.getColorData().get(i);
                if(colorData.getValue() == kelvin){
                    mColorTemperatureAdapter.selectItem(i);
                    hasSame = true;
                    break;
                }
            }
            if(!hasSame){
                mColorTemperatureAdapter.clearSelected();
            }
        }
    }

    private void switchOperation(int power){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, power);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setIsOpen(!roundSeekBar.isOpen());
                roundSeekBar.setOpenState(mDevice.getIsOpen());
                setStatusBySwitch(mDevice.getIsOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };

        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }else{
            LLHttpManager.operationDeviceGroup((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }
    }

    private void lightOperation(int light){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.LIGHT, light);
//        boolean isOpen = light > 0;
//        option.put("power", isOpen ? 1 : 0);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setLight(light);
                boolean isOpen = light > 0;
                if(isOpen != mDevice.getIsOpen()){
                    mDevice.setIsOpen(isOpen);
                    roundSeekBar.setOpenState(mDevice.getIsOpen());
                    setStatusBySwitch(mDevice.getIsOpen());
                }
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                roundSeekBar.setProgress(mDevice.getLight());
                roundSeekBar.setOpenState(mDevice.getLight() == 0 ? false : mDevice.getIsOpen());
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }else{
            LLHttpManager.operationDeviceGroup((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }

    }

    private void kelvinOperation(int kelvin){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.KELVIN, kelvin);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setKelvin(kelvin);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                colorTemperatureSeekBar.setColorTemp(mDevice.getKelvin());
                setKelvinItem(colorTemperatureSeekBar.getColorTemp());
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }else{
            LLHttpManager.operationDeviceGroup((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }
    }

    private void setStatusBySwitch(boolean isOpen){
        colorTemperatureSeekBar.setOpenState(isOpen);
        roundSeekBar.setOpenState(isOpen);
        if(mColorTemperatureAdapter != null){
            if(isOpen){
                setKelvinItem(colorTemperatureSeekBar.getColorTemp());
            }else{
                mColorTemperatureAdapter.clearSelected();
            }
        }
    }

    protected void updateView(){
        super.updateView();
        DeviceState deviceState = mDevice.getStateData();
        Integer light = deviceState.getStatus().getLight();
//        if(mDevice.isIsOnline()){
            roundSeekBar.setEnabled(true);
            Float progress = Float.valueOf(light);
            roundSeekBar.setProgress(progress.intValue());
            int kelvin = Integer.valueOf(deviceState.getStatus().getKelvin());
            colorTemperatureSeekBar.setColorTemp(kelvin);
            setKelvinItem(Integer.valueOf(kelvin));
            //如果设备亮度0的话，本地强制设置灯关
            setStatusBySwitch(progress == 0 ? false : mDevice.getIsOpen());
//        }else{
//            roundSeekBar.setEnabled(false);
//            setStatusBySwitch(false);
//        }
    }
}